import React from "react";
import './TodoHeader.css';
import { useState } from "react";
import { useDispatch } from "react-redux";
import { asyncAddTodo } from "../../../app/slices/todoSlice";

export default function TodoHeader() {
  //声明状态
  let [v, setV] = useState('');
  //获得 dispatch 函数
  let dispatch = useDispatch();
  //声明 keyup 事件回调
  let keyup = async (e) => {
    if(e.code === 'Enter'){
      //更新状态 dispatch 返回值是一个成功的 promise 对象
      let res = await dispatch(asyncAddTodo(v));
      //判断
      let status = res.type.split('/').pop();
      if(status === 'fulfilled'){
        alert('添加成功');
      }
      if(status === 'rejected'){
        alert('添加失败~');
      }
    } 
  }
  return (
    <div className="todo-header">
      <input onKeyUp={keyup} value={v} onChange={(e) => {setV(e.target.value)}} type="text" placeholder="请输入你的任务名称，按回车键确认" />
    </div>
  );
}
